package com.anonymous.community;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.GenericResponse;
import com.anonymous.community.api.model.RegisterRequest;
import com.anonymous.community.api.model.RegisterResponse;
import com.anonymous.community.api.model.SendCodeRequest;
import com.anonymous.community.databinding.ActivityRegisterBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.anonymous.community.utils.TokenManager;
import com.tencent.bugly.crashreport.CrashReport;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 注册Activity - 根据API v3.0.0文档
 * 流程：
 * 1. 发送验证码 POST /v1/api/auth/send-code
 * 2. 提交注册 POST /v1/api/auth/register
 */
public class RegisterActivity extends BaseActivity {

    private ActivityRegisterBinding binding;
    private ApiService apiService;
    private TokenManager tokenManager;
    private CountDownTimer countDownTimer;
    private boolean isCountingDown = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        apiService = ApiClient.getApiService();
        tokenManager = new TokenManager(this);

        setupViews();
    }

    private void setupViews() {
        // 发送验证码按钮
        binding.btnSendCode.setOnClickListener(v -> sendVerificationCode());
        
        // 注册按钮
        binding.btnRegister.setOnClickListener(v -> performRegister());
        
        // 返回登录
        binding.btnBack.setOnClickListener(v -> finish());
    }

    /**
     * 发送验证码
     */
    private void sendVerificationCode() {
        String email = binding.etEmail.getText().toString().trim();

        if (TextUtils.isEmpty(email)) {
            binding.tilEmail.setError("请输入邮箱");
            return;
        }

        if (!isValidEmail(email)) {
            binding.tilEmail.setError("请输入有效的邮箱地址");
            return;
        }

        binding.tilEmail.setError(null);
        hideErrorMessage();

        // 禁用按钮
        binding.btnSendCode.setEnabled(false);

        // 创建发送验证码请求
        SendCodeRequest request = new SendCodeRequest(email, "register");
        
        apiService.sendCode(request).enqueue(new Callback<GenericResponse>() {
            @Override
            public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Toast.makeText(RegisterActivity.this, "验证码已发送到您的邮箱", Toast.LENGTH_SHORT).show();
                    startCountDown();
                } else {
                    String errorMessage = extractErrorMessage(response);
                    if (TextUtils.isEmpty(errorMessage)) {
                        errorMessage = "发送验证码失败，请稍后重试";
                    }
                    showErrorMessage(errorMessage);
                    binding.btnSendCode.setEnabled(true);
                }
            }

            @Override
            public void onFailure(Call<GenericResponse> call, Throwable t) {
                showErrorMessage("网络连接失败，请检查网络设置");
                binding.btnSendCode.setEnabled(true);
            }
        });
    }

    /**
     * 执行注册
     */
    private void performRegister() {
        String email = binding.etEmail.getText().toString().trim();
        String username = binding.etUsername.getText().toString().trim();
        String password = binding.etPassword.getText().toString().trim();
        String confirmPassword = binding.etConfirmPassword.getText().toString().trim();
        String code = binding.etVerificationCode.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(email)) {
            binding.tilEmail.setError("请输入邮箱");
            return;
        }

        if (!isValidEmail(email)) {
            binding.tilEmail.setError("请输入有效的邮箱地址");
            return;
        }

        if (TextUtils.isEmpty(username)) {
            binding.tilUsername.setError("请输入用户名");
            return;
        }

        // 根据API文档，用户名要求：10-15个字符，只能包含字母、数字、中文
        if (username.length() < 10 || username.length() > 15) {
            binding.tilUsername.setError("用户名长度需为10-15个字符");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            binding.tilPassword.setError("请输入密码");
            return;
        }

        // 根据API文档，密码最少6个字符
        if (password.length() < 6) {
            binding.tilPassword.setError("密码至少需要6个字符");
            return;
        }

        if (!TextUtils.equals(password, confirmPassword)) {
            binding.tilConfirmPassword.setError("两次输入的密码不一致");
            return;
        }

        if (TextUtils.isEmpty(code)) {
            binding.tilVerificationCode.setError("请输入验证码");
            return;
        }

        // 清除错误信息
        clearErrors();
        hideErrorMessage();
        showLoading(true);

        // 创建注册请求
        RegisterRequest request = new RegisterRequest(email, username, password, code);

        // 发起注册请求
        apiService.register(request).enqueue(new Callback<RegisterResponse>() {
            @Override
            public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response) {
                showLoading(false);
                
                if (response.isSuccessful() && response.body() != null) {
                    RegisterResponse registerResponse = response.body();
                    
                    // 注册成功，保存token和用户信息
                    String token = registerResponse.getToken();
                    TokenManager.saveToken(RegisterActivity.this, token);
                    
                    // 保存用户信息
                    if (registerResponse.getUser() != null) {
                        tokenManager.saveUserInfo(
                            registerResponse.getUser().getId(),
                            registerResponse.getUser().getUsername(),
                            registerResponse.getUser().getRole()
                        );
                        
                        // 设置Bugly用户标识
                        CrashReport.setUserId(String.valueOf(registerResponse.getUser().getId()));
                        CrashReport.putUserData(getApplicationContext(), "username", registerResponse.getUser().getUsername());
                    }
                    
                    // 添加注册成功事件统计
                    CrashReport.postCatchedException(new Exception("Event: Register Success"));
                    
                    Toast.makeText(RegisterActivity.this, 
                        TextUtils.isEmpty(registerResponse.getMessage()) ? "注册成功" : registerResponse.getMessage(), 
                        Toast.LENGTH_SHORT).show();
                    
                    // 跳转到主页
                    navigateToMain();
                } else {
                    String errorMessage = extractErrorMessage(response);
                    if (TextUtils.isEmpty(errorMessage)) {
                        errorMessage = "注册失败，请检查输入信息";
                    }
                    showErrorMessage(errorMessage);
                }
            }

            @Override
            public void onFailure(Call<RegisterResponse> call, Throwable t) {
                showLoading(false);
                showErrorMessage("网络连接失败，请检查网络设置");
            }
        });
    }

    /**
     * 开始倒计时（60秒）
     */
    private void startCountDown() {
        isCountingDown = true;
        binding.btnSendCode.setEnabled(false);
        
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.btnSendCode.setText(String.format("%d秒后重试", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                binding.btnSendCode.setText("发送验证码");
                binding.btnSendCode.setEnabled(true);
                isCountingDown = false;
            }
        }.start();
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void clearErrors() {
        binding.tilEmail.setError(null);
        binding.tilUsername.setError(null);
        binding.tilPassword.setError(null);
        binding.tilConfirmPassword.setError(null);
        binding.tilVerificationCode.setError(null);
    }

    private void showLoading(boolean show) {
        binding.btnRegister.setEnabled(!show);
        binding.btnSendCode.setEnabled(!show && !isCountingDown);
        binding.etEmail.setEnabled(!show);
        binding.etUsername.setEnabled(!show);
        binding.etPassword.setEnabled(!show);
        binding.etConfirmPassword.setEnabled(!show);
        binding.etVerificationCode.setEnabled(!show);
    }

    private void showErrorMessage(String message) {
        binding.tvErrorMessage.setText(message);
        binding.tvErrorMessage.setVisibility(View.VISIBLE);
    }

    private void hideErrorMessage() {
        binding.tvErrorMessage.setVisibility(View.GONE);
    }

    /**
     * 从错误响应中提取 error 字段
     */
    private String extractErrorMessage(Response<?> response) {
        try {
            if (response != null && response.errorBody() != null) {
                String raw = response.errorBody().string();
                if (!TextUtils.isEmpty(raw)) {
                    try {
                        org.json.JSONObject obj = new org.json.JSONObject(raw);
                        if (obj.has("error")) {
                            return obj.optString("error");
                        }
                    } catch (Exception jsonEx) {
                        return raw;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        return null;
    }

    private void navigateToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "注册页";
    }
}

